package edu.gatech.cs2340.tigershroud;

import java.io.IOException;
import java.util.List;
import java.util.Locale;


import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

/**
 * Handles all map display properties for the current user
 * @author 
 *
 */
public class MapViewActivity extends MapActivity implements LocationListener
{

	LocationManager locationManager;
	MapView mapView;
	MyLocationOverlay myLocationOverlay;
	TodoDataSource ds;
	MapController mapController;
	Geocoder geocoder;
	List<Task> tasks;
	GeoPoint y;
	OverlayItem o;
	MyOverlays itemizedoverlay;
	MyOverlays itemizedoverlay2;
	Task[] taskArray;
	List<Overlay> mapOverlays;
	MasterControlClass mcc;

	/**
	 * Constructor for the map activity the context is received from the application
	 * @param context
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	 {
	 super.onCreate(savedInstanceState);
	 setContentView(R.layout.map);
	 
	 ds = new TodoDataSource(this);
	 ds.open();
	 mcc = new MasterControlClass();
	 
	 mapView = (MapView) findViewById(R.id.mapview);
	 mapView.setBuiltInZoomControls(true);
	 mapOverlays = mapView.getOverlays();
	 
	 tasks = ds.getAllTaskForUser("ASC");
	 if(tasks.get(0).getDescription() == null){
		 tasks.remove(0);
	 } else {
	 taskArray = new Task[tasks.size()];
	 Drawable drawable = this.getResources().getDrawable(R.drawable.point);
	 itemizedoverlay = new MyOverlays(drawable,this);
	 generateMapPoints();
	 mapOverlays.add(itemizedoverlay);
	 }

	mapView.setSatellite(true);
	mapController = mapView.getController();
	mapController.setZoom(10); // Zoom 1 is world view

	locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
		
		 
	myLocationOverlay = new MyLocationOverlay(this, mapView);
	myLocationOverlay.enableMyLocation();
	mapOverlays.add(myLocationOverlay);

		myLocationOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				mapController.animateTo(
						myLocationOverlay.getMyLocation());
				mapController.setCenter(myLocationOverlay.getMyLocation());
					
			}
		});
	 }
	
	/**
	 * When the map activity is refreshed the map overlays are refreshed
	 */
	
	public void refresh()
    {
		tasks = ds.getAllTaskForUser("ASC");
		taskArray = new Task[tasks.size()];
		mapView.invalidate();
		mapOverlays.remove(1);
		

		Drawable drawable = this.getResources().getDrawable(R.drawable.point);
		itemizedoverlay = new MyOverlays(drawable,this);
		generateMapPoints();
		mapOverlays.add(itemizedoverlay);
    }
	
	/**
	 * When the map activity is displayed the route is not displayed
	 */
	 @Override
	 protected boolean isRouteDisplayed()
	 {
	 return false;
	 }
	 
	 /**
		 * When the map activity is resumed the user location is refreshed
		 */
	 @Override
	  protected void onResume() {
	    super.onResume();
	    if(tasks.size() > 0){
	    	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); //<7>
	    }
	  }

	 /**
		 * When the map activity is paused the user location is no longer updated
		 */
	  @Override
	  protected void onPause() {
	    super.onPause();
	    if(tasks.size() > 0){
	    	locationManager.removeUpdates(this); //<8>
	    	refresh();
	    }
	  }

	  /**
		 * When the user moves the user location is updated
		 * @param location the user's current location
		 */
	  
	  public void onLocationChanged(Location location) { //<9>
		 
		  myLocationOverlay.enableMyLocation();
		  List<Overlay> overlays = mapView.getOverlays();
          myLocationOverlay = new MyLocationOverlay(this,mapView);
          overlays.add(myLocationOverlay);
         
	      int latitude = (int)(location.getLatitude() * 1E6);
	      int longitude = (int)(location.getLongitude() * 1E6);

	      GeoPoint point = new GeoPoint(latitude,longitude);
	      mapController.animateTo(point); //<11>
	  
	  }
	  /**
	   * Auto-generated method to determine behavior when the Location Manger is disabled
	   * Default behavior is to do nothing
	   *@param arg0 string message that is passed on disable
	   */

	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}
	/**
	   * Auto-generated method to determine behavior when the Location Manger is enabled
	   * Default behavior is to do nothing
	   *@param arg0 string message that is passed on enable
	   */
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}
	/**
	   * Auto-generated method to determine behavior when the Location Manger status changes
	   * Default behavior is to do nothing
	   *@param arg0 string message that is passed on status change
	   *@param arg1 int representing
	   *@param arg2 Bundle obtained from Activity   */
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}
	
	/**
	   *Method that obtains an address given address
	   *@param address a String representing a physical address
	   *@return A GeoPoint that represents the address with longitude and latitude coordinates	   */
	public GeoPoint getLocationFromAddress(String address) throws Exception
	{
			  address = address.trim();
			  
			  address = address.replaceAll("No address", "");
			  address = address.replaceAll("No description", "");
			  address = address.replaceAll("No city", "");
			  address = address.replaceAll("No state", "");
			  address = address.replaceAll("No zipcode", "");
			  
			  
			  int lat = (int)(33.7489954*1E6);
			  int lon = (int)(-84.3879824*1E6);
			// Reverse geocode the postal address to get a location.
			    if (address != null && Geocoder.isPresent()) {
			      Geocoder geocoder = new Geocoder(this, Locale.getDefault());
			      try {
			        List<Address> addressResult = geocoder.getFromLocationName(address, 1);
			        if (!addressResult.isEmpty()) {
			          Address resultAddress = addressResult.get(0);
			          lat = (int)(resultAddress.getLatitude()*1E6);
			          lon = (int)(resultAddress.getLongitude()*1E6);
			        }
			      } catch (IOException e) {
			        Log.d("Contact Location Lookup Failed", e.getMessage());
			      }
			    }
			    GeoPoint result = new GeoPoint(lat, lon);
		return result;
				  }
	
	/**
	 * Takes the global list of Tasks, converts their address to GeoPoints and uses those GeoPoints 
	 * to initialize MapOverlayItems. Those intialized MapOverlayItems are added to an overlay on the map
	 */
			
    public void generateMapPoints()
    {
    	
    	taskArray = tasks.toArray(taskArray);
   	 GeoPoint gp =  new GeoPoint ((int)(33.7489954*1E6), (int)(-84.3879824*1E6));
   	 for(int i= 0; i<taskArray.length; i++)
   	 {
   		 String address = "Atlanta";
   		 
   	 try{
   		 address = (taskArray[i].getAddress() + " "+ taskArray[i].getCity() + " " + 
   				 taskArray[i].getState()+ " " + taskArray[i].getZipCode());
   		 gp = getLocationFromAddress(address);
   	 	}
   	 catch (Exception e)
   	 {
   		 e.printStackTrace();
   	 }
   	 
   	 itemizedoverlay.addOverlay(new OverlayItem(gp, taskArray[i].getTaskName(), taskArray[i].getDescription()));
   	 }
    	
    }

			  //String = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false";
			        //URL htmlReq = new URL("http://maps.googleapis.com/maps/geo?q=" + address + "&output=csv&sensor=false&key=0tWOMJHgLZxGtfl9fTB2CqDQluLCqCWx22k4wCw");
			        //URLConnection conn = htmlReq.openConnection();
			   
			        //BufferedReader reader = new BufferedReader(
			  //new InputStreamReader(openHttpConnection
			  //("http://maps.googleapis.com/maps/geo?q=" + address + "&output=csv&sensor=
			  //false&key=0tWOMJHgLZxGtfl9fTB2CqDQluLCqCWx22k4wCw")));
			  
//			  URL url = new URL("http://maps.googleapis.com/maps/geo?q=" + address + "&output=csv&sensor=false&key=0tWOMJHgLZxGtfl9fTB2CqDQluLCqCWx22k4wCw");
//              URLConnection conn = url.openConnection();
//              // Get the response
//              BufferedReader reader = new BufferedReader(new 
//InputStreamReader(conn.getInputStream()));
//			       
//			  try {
//			         String line;
//			         while ((line = reader.readLine()) != null) {
//			              String[] RowData = line.split(",");
//			              lat = (int)(Double.parseDouble(RowData[2]) * 1E6);
//			              lon = (int)(Double.parseDouble(RowData[3]) * 1E6);
//			              Message lmsg;
//	                        lmsg = new Message();
//	                        lmsg.obj = line;
//	                        lmsg.what = 0;
//	                        GetWebPage.this.h.sendMessage(lmsg);
//
//			         }
//			        reader.close();
//			     }
//			     catch (IOException ex) {
//			         // handle exception
//			     }
			  /*   
			  Toast.makeText(getApplicationContext(), 
						"Location is: " + lat + lon, 
						Toast.LENGTH_LONG).show();*/
	
//	private InputStream openHttpConnection(String urlString) throws IOException
//			{
//				InputStream in = null;
//				int response = -1;
//				URL url = new URL(urlString);
//				URLConnection conn = url.openConnection();
//				if (!(conn instanceof HttpURLConnection))
//				throw new IOException("Not an HTTP connection");
//				try{
//					HttpURLConnection httpConn = (HttpURLConnection) conn;
//					httpConn.setAllowUserInteraction(false);
//					httpConn.setInstanceFollowRedirects(true);
//					httpConn.setRequestMethod("GET");
//					httpConn.connect();
//				response = httpConn.getResponseCode();
//				if (response == HttpURLConnection.HTTP_OK)
//				{in = httpConn.getInputStream(); }
//				}
//			catch (Exception ex)
//			{
//				throw new IOException("Error connecting");
//			}
//	return in;
//			}
//	
	
	}
	

	
